package com.snail.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.snail.mapper.SysUserRoleMapper;
import com.snail.model.pojo.user.SysRole;
import com.snail.model.pojo.user.SysUserRole;
import com.snail.service.SysRoleService;
import com.snail.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户角色服务实现类
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 对用户进行角色分配
     *
     * @param userId  用户ID
     * @param roleIds 可能会存在多个角色id
     */
    @Override
    @Transactional //避免只进行了对多余的关系进行删除，没有进行新增关系的添加
    public void addUserToRole(Long userId, List<Long> roleIds) {
        // 先清除用户原有的角色绑定关系
        //LambdaQueryWrapper 是用来拼接各种查询条件的，比如where ，order等
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        // 相当于 delete from sys_user_role where user_id = #{userId}
        this.remove(wrapper.eq(SysUserRole::getUserId, userId));

        // 构建并插入新关系
        List<SysUserRole> list = new ArrayList<>();
        for (Long roleId : roleIds) {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            list.add(userRole);
        }
        // saveBatch 是批量插入的方法
        this.saveBatch(list);
    }

    /**
     * 获取用户的角色id列表
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public List<Long> getRoleIdsByUserId(Long userId) {
        //lambdaQuery() 相当于构建了一个lambdaQueryWrapper
        return this.lambdaQuery()
                .eq(SysUserRole::getUserId, userId)
                .list()
                .stream()
                .map(SysUserRole::getRoleId)
                .collect(Collectors.toList());
    }

    /**
     * 获取用户的角色code列表
     */
    @Override
    public List<String> getRoleCodesByUserId(Long userId) {
        List<Long> roleIds = getRoleIdsByUserId(userId);

        return sysRoleService.lambdaQuery()
                .in(SysRole::getId, roleIds)
                .list()
                .stream()
                .map(SysRole::getCode)
                .collect(Collectors.toList());
    }

    @Override
    public Map<Long, List<Long>> getAllUserRoleMap() {
        // 1. 查询所有用户角色关系

        List<SysUserRole> list = this.lambdaQuery().
                select(SysUserRole::getUserId, SysUserRole::getRoleId).list();
        // 2. 转换为Map<userId, List<roleId>>
        return list.stream().collect(Collectors.groupingBy(
                SysUserRole::getUserId,
                Collectors.mapping(SysUserRole::getRoleId, Collectors.toList())
        ));
    }

    /**
     * 根据角色code获取角色id列表
     */
    @Override
    public List<Long> getRoleIdsByCodes(List<String> roleCodes) {
       return sysRoleService.lambdaQuery().in(SysRole::getCode, roleCodes).list()
                .stream().map(SysRole::getId).collect(Collectors.toList());

    }

}
